package com.peak.distribution.config.security;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.peak.distribution.jms.JmsProducerHandler;
import com.peak.spring.boot.api.web.JsonMessage;
import com.peak.spring.boot.builder.web.JsonBuilder;
import com.peak.spring.boot.tools.Servlets;

@Component
public class SessionAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
	private JmsProducerHandler jmsProducerHandler;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		SessionUser user = (SessionUser) authentication.getPrincipal();
		
		// 记录登录日志
		jmsProducerHandler.sendLoginJms(request, Boolean.TRUE);

		// 如果是Ajax登录
		if (Servlets.isAjax(request)) {
			super.clearAuthenticationAttributes(request);
			Map<String, Object> content = Maps.newHashMap();
			content.put("url", user.getDefaultSuccessUrl());
			JsonMessage msg = JsonBuilder.message().success().content(content).build();
			Servlets.sendJson(response, msg);
		} else {
			// 根据角色中配置的页面跳转
			super.setDefaultTargetUrl(user.getDefaultSuccessUrl());
			super.setAlwaysUseDefaultTargetUrl(true);
			super.onAuthenticationSuccess(request, response, authentication);
		}

	}

}
